var jsonRequestData = {
    form_id: "1",
    search_value: "",
    field: "0",
    start: "0",
    date_field: "",
    date_from: "",
    date_to: "",
    "column-sort": "",
    "column-sort-type": "",
    "multi_search":[]
}
var jsonOrgchartData = {
    search_value: "",
}
var jsonWorkflowData = {
    search_value: "",   
}
var jsonFormData = {
    search_value: "",   
}
var jsonReportData = {
    search_value: "",   
}
var jsonCustomReportData = {
    search_value: "",   
}
var columnSort = [];
var dashboardItemContainer = ".fl-table-wrapper";
$(document).ready(function() {
    //request
    //default load
    $(".dataTable").each(function() {
        GetRequestsDataTable.defaultData(jsonRequestData, this);
    })
    //end default load

    $("body").on("click",".recordsDatatable tbody tr td:not(td:first-child)",function(e){
       var href = $(this).closest("tr").find(".linkTrigger").attr("href");
       window.location = href;
    })

    //sort
    $("body").on("click",".recordsDatatable th",function(){
        var flSortdiv = $('<div class="flSortdiv"></div>');
        //console.log(flSortdiv);
        var cursor = $(this).css("cursor");
        jsonRequestData['column-sort'] = $(this).attr("field_name");
        if($(this).attr("field_name")=="" || $(this).attr("field_name")==undefined || cursor=="col-resize"){
            return;
        }
        var indexcolumnSort = columnSort.indexOf($(this).attr("field_name"));

        $(this).closest(dashboardItemContainer).find(".sortable-image").html("");
        if(indexcolumnSort==-1){
            columnSort.push($(this).attr("field_name"))
            $(this).find(".sortable-image").html("<i class='fa fa-sort-asc'></i>")
            jsonRequestData['column-sort-type'] = "ASC";
        }else{
            columnSort.splice(indexcolumnSort,1);
            $(this).find(".sortable-image").html("<i class='fa fa-sort-desc'></i>")
            jsonRequestData['column-sort-type'] = "DESC";
        }
        
        var tableID = $(this).closest(dashboardItemContainer).find(".dataTable").attr("id");
        $(this).closest(dashboardItemContainer).find(".dataTable").dataTable().fnDestroy();
        GetRequestsDataTable.defaultData(jsonRequestData, this);
    })
    //search
    $(".searchRequestUsersValue").keydown(function(e) {
        if (e.keyCode == "13") {
            jsonRequestData['search_value'] = $(this).val();
            jsonRequestData['multi_search'] = "";
            // jsonRequestData['field'] = $(this).closest(dashboardItemContainer).find(".searchRequestUsersField").val()
            jsonRequestData['field'] = "0";
            var tableID = $(this).closest(dashboardItemContainer).find(".dataTable").attr("id");
            $(this).closest(dashboardItemContainer).find(".dataTable").dataTable().fnDestroy();
            GetRequestsDataTable.defaultData(jsonRequestData, this);
            // $(this).closest(dashboardItemContainer).append(datatableClone)

            RequestFilter2.showFilterConfirmation(this);
        }
    })
    $(".searchRequestUsersButton").click(function() {
        jsonRequestData['search_value'] = $(this).closest(dashboardItemContainer).find(".searchRequestUsersValue").val();
        jsonRequestData['multi_search'] = "";
        // jsonRequestData['field'] = $(this).closest(dashboardItemContainer).find(".searchRequestUsersField").val()
        jsonRequestData['field'] = "0";
        $(this).closest(dashboardItemContainer).find(".dataTable").dataTable().fnDestroy();
        GetRequestsDataTable.defaultData(jsonRequestData, this);
        RequestFilter2.showFilterConfirmation(this);
    })
    $(".filterRequestsUser").change(function() {
        jsonRequestData['search_value'] = $(this).find("option:selected").attr("search_value");
        jsonRequestData['field'] = $(this).find("option:selected").attr("search_field");
        jsonRequestData['date_field'] = $(this).find("option:selected").attr("date_field");
        jsonRequestData['date_from'] = $(this).find("option:selected").attr("date_from");
        jsonRequestData['date_to'] = $(this).find("option:selected").attr("date_to");
        jsonRequestData['multi_search'] = $(this).find("option:selected").attr("multi_search");
        $(this).closest(dashboardItemContainer).find(".dataTable").dataTable().fnDestroy();
        GetRequestsDataTable.defaultData(jsonRequestData, this);
        if($(this).val()==0){
            $(this).closest(dashboardItemContainer).find(".cancelFC").fadeOut();
        }else{
            $(this).closest(dashboardItemContainer).find(".cancelFC").fadeIn();
        }
        $(this).closest(dashboardItemContainer).find(".saveFC").fadeOut();
    })
    $(".requestFilterSettings").click(function() {
        RequestFilter2.settingsModal(this);
    })
    $("body").on("click", ".deleteFilter", function() {
        var id = $(this).attr("data-id");
        RequestFilter2.deleteFilter(id,this);
    })

    //ADVANCE FILTER
    AdvanceFilter2.addFilter();
    AdvanceFilter2.deleteFilter();
    

    $("body").on("click", ".advanceFilterDialog", function() {
        AdvanceFilter2.showDialog(this);
    })
    $("body").on("click", "#advanceFilter", function() {
        AdvanceFilter2.filter(this);
    })
    $("body").on("click", "#clearValue", function() {
        AdvanceFilter2.clearFilterFields();
    })
    $("body").on("click", ".cancelFC", function() {
        jsonRequestData['search_value'] = "";
        jsonRequestData['field'] = 0;
        jsonRequestData['date_field'] = "";
        jsonRequestData['date_from'] = "";
        jsonRequestData['date_to'] = "";
        jsonRequestData['multi_search'] = "";
        $(this).closest(dashboardItemContainer).find(".loadRF").val(0);
        $(this).closest(dashboardItemContainer).find(".dataTable").dataTable().fnDestroy();
        GetRequestsDataTable.defaultData(jsonRequestData, this);
        RequestFilter2.hideFilterConfirmation(this);
    })
    $(".saveFC").click(function() {
        RequestFilter2.setConfirmation(this);
    })
    $("body").on("click", "#saveRF", function() {
        RequestFilter2.saveRF(this);
    })
    //end request

    //orgchart
    $("body").on("keyup","#txtSearchOrgchartDatatable",function(e){
        $(".dataTable_orgchart").dataTable().fnDestroy();
        jsonOrgchartData['search_value'] = $(this).val();
        GetOrgchartDataTable.defaultData();
    })
    //load
    GetOrgchartDataTable.defaultData();
    //sort
    $("body").on("click",".dataTable_orgchart th",function(){
        var cursor = $(this).css("cursor");
        jsonOrgchartData['column-sort'] = $(this).attr("field_name");
        if($(this).attr("field_name")=="" || $(this).attr("field_name")==undefined){
            return;
        }
        var indexcolumnSort = columnSort.indexOf($(this).attr("field_name"));

        $(this).closest(".dataTable_orgchart").find(".sortable-image").html("");
        if(indexcolumnSort==-1){
            columnSort.push($(this).attr("field_name"))
            $(this).find(".sortable-image").html("<i class='fa fa-sort-asc'></i>")
            jsonOrgchartData['column-sort-type'] = "ASC";
        }else{
            columnSort.splice(indexcolumnSort,1);
            $(this).find(".sortable-image").html("<i class='fa fa-sort-desc'></i>")
            jsonOrgchartData['column-sort-type'] = "DESC";
        }
        
        $(".dataTable_orgchart").dataTable().fnDestroy();
        GetOrgchartDataTable.defaultData();
    })
    //end orgchart


    //workflow
    $("body").on("keyup","#txtSearchWorkflowDatatable",function(e){
        $(".dataTable_workflow").dataTable().fnDestroy();
        jsonWorkflowData['search_value'] = $(this).val();
        GetWorkflowDataTable.defaultData();
    })
    //load
    GetWorkflowDataTable.defaultData();
    //sort
    $("body").on("click",".dataTable_workflow th",function(){
        var cursor = $(this).css("cursor");
        jsonWorkflowData['column-sort'] = $(this).attr("field_name");
        if($(this).attr("field_name")=="" || $(this).attr("field_name")==undefined){
            return;
        }
        var indexcolumnSort = columnSort.indexOf($(this).attr("field_name"));

        $(this).closest(".dataTable_workflow").find(".sortable-image").html("");
        if(indexcolumnSort==-1){
            columnSort.push($(this).attr("field_name"))
            $(this).find(".sortable-image").html("<i class='fa fa-sort-asc'></i>")
            jsonWorkflowData['column-sort-type'] = "ASC";
        }else{
            columnSort.splice(indexcolumnSort,1);
            $(this).find(".sortable-image").html("<i class='fa fa-sort-desc'></i>")
            jsonWorkflowData['column-sort-type'] = "DESC";
        }
        
        $(".dataTable_workflow").dataTable().fnDestroy();
        GetWorkflowDataTable.defaultData();
    })
    //end workflow


    //form
    $("body").on("keyup","#txtSearchFormDatatable",function(e){
        $(".dataTable_form").dataTable().fnDestroy();
        jsonFormData['search_value'] = $(this).val();
        GetFormDataTable.defaultData();
    })
    //load
    GetFormDataTable.defaultData();
    //sort
    $("body").on("click",".dataTable_form th",function(){
        var cursor = $(this).css("cursor");
        jsonFormData['column-sort'] = $(this).attr("field_name");
        if($(this).attr("field_name")=="" || $(this).attr("field_name")==undefined){
            return;
        }
        var indexcolumnSort = columnSort.indexOf($(this).attr("field_name"));

        $(this).closest(".dataTable_form").find(".sortable-image").html("");
        if(indexcolumnSort==-1){
            columnSort.push($(this).attr("field_name"))
            $(this).find(".sortable-image").html("<i class='fa fa-sort-asc'></i>")
            jsonFormData['column-sort-type'] = "ASC";
        }else{
            columnSort.splice(indexcolumnSort,1);
            $(this).find(".sortable-image").html("<i class='fa fa-sort-desc'></i>")
            jsonFormData['column-sort-type'] = "DESC";
        }
        
        $(".dataTable_form").dataTable().fnDestroy();
        GetFormDataTable.defaultData();
    })
    //end form


    //report
    //form
    $("body").on("keyup","#txtSearchReportDatatable",function(e){
        $(".dataTable_report").dataTable().fnDestroy();
        jsonReportData['search_value'] = $(this).val();
        GetReportDataTable.defaultData();
    })
    //load
    GetReportDataTable.defaultData();
    //sort
    $("body").on("click",".dataTable_report th",function(){
        var cursor = $(this).css("cursor");
        jsonReportData['column-sort'] = $(this).attr("field_name");
        if($(this).attr("field_name")=="" || $(this).attr("field_name")==undefined){
            return;
        }
        var indexcolumnSort = columnSort.indexOf($(this).attr("field_name"));

        $(this).closest(".dataTable_report").find(".sortable-image").html("");
        if(indexcolumnSort==-1){
            columnSort.push($(this).attr("field_name"))
            $(this).find(".sortable-image").html("<i class='fa fa-sort-asc'></i>")
            jsonReportData['column-sort-type'] = "ASC";
        }else{
            columnSort.splice(indexcolumnSort,1);
            $(this).find(".sortable-image").html("<i class='fa fa-sort-desc'></i>")
            jsonReportData['column-sort-type'] = "DESC";
        }
        
        $(".dataTable_report").dataTable().fnDestroy();
        GetReportDataTable.defaultData();
    })
    //end report

    //customize report
    $("body").on("keyup","#txtSearchCustomReportDatatable",function(e){
        $(".dataTable_custom_report").dataTable().fnDestroy();
        jsonCustomReportData['search_value'] = $(this).val();
        GetCustomReportDataTable.defaultData();
    })
    GetCustomReportDataTable.defaultData();
})
GetRequestsDataTable = {
    "defaultData": function(jsonRequestData, obj) {
        var form_header = $(obj).closest(dashboardItemContainer).find(".form-header").text();
        var form_id = $(obj).closest(dashboardItemContainer).find(".form_id").val();
        jsonRequestData['form_id'] = form_id;
        this.removeDataTableAttr(obj);

        var oTable = $(obj).closest(dashboardItemContainer).find(".dataTable").dataTable({
            "sDom": 'Rlfrtip',
            // "sScrollY": "400px",
            "oLanguage": {
                "sProcessing": '<div class="spinner load_m"> '+
                       '<div class="bar1"></div> '+
                       '<div class="bar2"></div> '+
                       '<div class="bar3"></div> '+
                       '<div class="bar4"></div> '+
                       '<div class="bar5"></div> '+
                       '<div class="bar6"></div> '+
                      '<div class="bar7"></div> '+
                      '<div class="bar8"></div> '+
                      '<div class="bar9"></div> '+
                      '<div class="bar10"></div> '+
                 '</div>'
            },
            "oColReorder": {
                "iFixedColumns": 1,
                "fnReorderCallback": function () {
                    // alert('Columns reordered');
                    var customView = [];
                    var field_name = "";
                    var field_label = "";
                    var field_width = "";
                    $(obj).closest(dashboardItemContainer).find(".dataTable th").each(function(){
                        field_label = $(this).text();
                        field_name = $(this).attr("field_name");
                        field_width = $(this).css("width");
                        if(field_label!=""){
                            customView.push({
                                "field_name":field_name,
                                "field_label":field_label,
                                "width":field_width
                            });
                        }
                    });
                    customView = JSON.stringify(customView);
                    ui.block();
                    $.post("/ajax/search",{action:"saveCustomView",form_id:form_id,customView:customView},function(data){
                        ui.unblock();
                    })
                },
                "fnResizeCallback" : function(){
                    // alert("Callback Resize");
                    var customView = [];
                    var field_name = "";
                    var field_label = "";
                    var field_width = "";
                    $(obj).closest(dashboardItemContainer).find(".dataTable th").each(function(){
                        field_label = $(this).text();
                        field_name = $(this).attr("field_name");
                        field_width = $(this).css("width");
                        if(field_label.trim()!=""){
                            customView.push({
                                "field_name":field_name,
                                "field_label":field_label,
                                "width":field_width
                            });
                        }
                    });
                    customView = JSON.stringify(customView);
                    ui.block();
                    $.post("/ajax/search",{action:"saveCustomView",form_id:form_id,customView:customView},function(data){
                        ui.unblock();
                    })
                }
            },
            "bLengthChange": false,
            "bFilter": false,
            "bProcessing": true,
            "bServerSide": true,
            "sPaginationType": "full_numbers",
            "bSort": false,
            // "aoColumns": [
            //     {"mData": "TrackNo"},
            //     {
            //         "mData": function(source, type, val) {
            //             return source['first_name'] + " " + source['last_name'];
            //         }
            //     },
            //     {
            //         "mData": function(source, type, val) {
            //             var result = "";
            //             if (form_header && typeof form_header == "string") {
            //                 form_header = JSON.parse(form_header);
            //             }
            //             if (form_header == null || form_header == "") {
            //                 result = '<i ></i> <strong style="font-size: 10px;color: rgb(241, 79, 79);">No Header Information available</strong> ';
            //             } else {
            //                 var fieldValue = '';
            //                 for (var a in form_header) {
            //                     field_name = form_header[a]['field_name'];

            //                     if (field_name.indexOf('[]') >= 0) {
            //                         field_name = field_name.split('[]').join('');
            //                         console.log(field_name);

            //                         if (source['' + field_name + ''] != '') {
            //                             fieldValue = source['' + field_name + ''].split('|^|').join(',');
            //                         } else {
            //                             fieldValue = '';
            //                         }

            //                     } else {
            //                         fieldValue = source['' + field_name + ''];
            //                     }
            //                     result += '<i class="fa fa-circle" style="font-size:7px"></i> <strong class="detailed_info" style="font-size: 10px;color: #6D6868;">' + fieldValue + '</strong> ';
            //                 }
            //             }
            //             return result;
            //         }
            //     },
            //     {"mData": "form_status"},
            //     {"mData": "DateCreated"},
            //     {
            //         "mData": function(data, type, val) {
            //             var result = "";
            //             var starred_class = "fa fa-star-o";
            //             var starred = 0;
            //             if (data[0]['starred'] > 0) {
            //                 starred_class = "fa fa-star";
            //                 starred = data[0]['starred'];
            //             }
            //             result +=
            //                     '<a href="/user_view/workspace?view_type=request&formID=' + form_id + '&requestID=' + data['request_id'] + '&trackNo=' + data['TrackNo'] + '"><button class="tip fa fa-eye btn-basicBtn fl-basicsecondary-btn padding_5 cursor" style="margin-right:3px" form-id = "' + form_id + '" request-id="' + data['request_id'] + '" data-original-title="View Form"></button></a>' +
            //                     '<button class="tip ' + starred_class + ' btn-basicBtn padding_5 cursor fl-basicsecondary-btn starred" style="margin-right:3px" data-id="' + data['request_id'] + '" id="starred_' + data['request_id'] + '" data-starred="' + starred + '" data-original-title="Starred Request"></button>' +
            //                     '<button class="fa fa-comment btn-basicBtn padding_5 fl-basicsecondary-btn cursor showReply tip" data-type="1" data-f-id="' + form_id + '" data-id="' + data['request_id'] + '" data-original-title="Add/View Comments" ></button> ' +
            //                     '<button class="tip fa fa-book btn-basicBtn padding_5 fl-basicsecondary-btn cursor viewAuditLogs" style="margin-right:3px" data-request-id="' + data['request_id'] + '" data-form-id="' + form_id + '" data-original-title="Audit Logs"></button>';
            //             if (data[2].buttons != '' && data[2].buttons != 'null' && data[2].buttons != null) {
            //                 result += "<button class='tip fa fa-gear btn-basicBtn padding_5 fl-basicsecondary-btn cursor' button-action-data='" + data[2].buttons + "' button-request-id='" + data['ID'] + "'button-workflow-id='" + data['Workflow_ID'] + "'  button-requestor-id='" + data['Requestor'] + "' button-processor-id='" + data['Processor'] + "' button-type='action' data-original-title='Please select an Action'></button>";
            //             }
            //             return result;
            //         }
            //     },
            // ],
            "sAjaxSource": "/ajax/search",
            "fnServerData": function(sSource, aoData, fnCallback) {
                aoData.push({"name": "action", "value": "getRequestDataTable"});
                aoData.push({"name": "id", "value": form_id});
                aoData.push({"name": "search_value", "value": jsonRequestData['search_value']});
                aoData.push({"name": "field", "value": jsonRequestData['field']});
                aoData.push({"name": "multi_search", "value": jsonRequestData['multi_search']});
                aoData.push({"name": "start", "value": jsonRequestData['start']});
                aoData.push({"name": "date_field", "value": jsonRequestData['date_field']});
                aoData.push({"name": "date_from", "value": jsonRequestData['date_from']});
                aoData.push({"name": "date_to", "value": jsonRequestData['date_to']});
                aoData.push({"name": "column-sort", "value": jsonRequestData['column-sort']});
                aoData.push({"name": "column-sort-type", "value": jsonRequestData['column-sort-type']});
                
                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function(data) {
                        // console.log(data)
                        // return;
                        // $(obj).find("tbody tr td:not(td:first-child)").css({
                        //     "cursor":"pointer"
                        // });
                        fnCallback(data);
                    }
                });
            },
            "fnInitComplete": function(oSettings, json) {
                $('[button-type="action"]').each(function() {
                    var actions = JSON.parse($(this).attr('button-action-data'));
                    var request_id = $(this).attr('button-request-id');
                    var workflow_id = $(this).attr('button-workflow-id');
                    var requestor_id = $(this).attr('button-requestor-id');
                    var processor_id = $(this).attr('button-processor-id');


                    var html_action = '<ul style="padding:3px;">';
                    for (var index in actions) {
                        html_action += '<a style="padding:3px;" href="#" class="requestlink" link-type="request-actions" request-id="' + request_id + '"form-id="' + form_id + '" workflow-id="' + workflow_id + '" node-id="' + actions[index].child_id + '"><li>' + actions[index].button_name + '</li></a>';
                    }
                    html_action += '</ul>';

                    $(this).popover({
                        placement: 'bottom',
                        title: 'Please select Action',
                        html: true,
                        content: html_action
                    });

                });
                $(obj).closest(dashboardItemContainer).find(".dataTable").find(".sorting_disabled").first().css({
                    cursor: "auto"
                })
                $(".tip").tooltip();
                $(obj).closest(dashboardItemContainer).find(".dataTable_widget").html("")
                $(obj).closest(dashboardItemContainer).find(".dataTables_info").appendTo($(obj).closest(dashboardItemContainer).find(".dataTable_widget"));
                $(obj).closest(dashboardItemContainer).find(".dataTables_paginate").appendTo($(obj).closest(dashboardItemContainer).find(".dataTable_widget"));
                // $(obj).closest(dashboardItemContainer).find(".dataTables_info").appendTo($(obj).closest(dashboardItemContainer));
                // $(obj).closest(dashboardItemContainer).find(".dataTables_paginate").appendTo($(obj).closest(dashboardItemContainer));

                // $(obj).find("tbody tr td:not(td:first-child)").css({
                //     "cursor":"pointer"
                // });
            }
        });
        return oTable;
    },
    removeDataTableAttr: function(obj) {
        var tableID = $(obj).closest(dashboardItemContainer).find(".dataTable").attr("id");
        $(obj).closest(dashboardItemContainer).find("#" + tableID + "_wrapper").remove();
    }

}
RequestFilter2 = {
    createSettingsModal: function(requestFilters, obj) {
        var form_id = $(obj).closest(dashboardItemContainer).attr("form_id");
        var text = "";
        var id = "";
        var ret = '<h3 class="fl-margin-bottom"><i class="icon-trash"></i> Remove Filter</h3>';
        ret += '<div class="hr"></div>';
        ret += '<div id="" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; overflow: hidden;" class="ps-container">';
        ret += '<div class="content-dialog fl-remove-filter" style="width: 100%; margin-bottom: 0px;">';
        ret += '<table class="fl-filter-list" style="width:100%;">';
        ret += '<thead>';
        ret += '<tr style="font-weight:bold;">';
        ret += '<br/>';
        ret += '<th style="width:70%;font-weight:bold;">Title of you filter</th>';
        ret += '<th style="font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>';
        ret += '</tr>';
        ret += '</thead>';
        ret += '<tbody>';
        for (var i in requestFilters) {
            if (requestFilters[i]['value'] != 0 && requestFilters[i]['value'] != undefined) {
                text = requestFilters[i]['text'];
                id = requestFilters[i]['value'];
                ret += '<tr id="row_' + id + '">';
                ret += '<td width="100%"><div class="fl-table-ellip">' + text + '</div></td>';
                ret += '<td style="text-align:center;">';
                ret += '<i class="tip padding_5 cursor fa fa-times deleteFilter" form_id="' + form_id + '" data-id="' + id + '" data-original-title="Delete"></i>';
                // ret += '<button class="tip btn-basicBtn padding_5 cursor icon-edit editFilter" data-id="'+ id +'" style="margin-right:3px;" data-original-title="Delete"></button>';
                ret += '</td>';
                ret += '</tr>';
            }
        }
        ret += '</tbody>';
        ret += '</table>';
        ret += '</div>';
        ret += '<div class="fields" style="">';
        ret += '<div class="label_basic"></div>';
        ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
        ret += ' <input type="button" class="btn-basicBtn" id="popup_cancel" value="Close">';
        ret += '</div>';
        ret += '</div>';
        return ret;
    },
    settingsModal: function(obj) {
        var requestFilters = $(obj).closest(dashboardItemContainer).find(".loadRF").find("option");
        var ret = this.createSettingsModal(requestFilters,obj);
        if (requestFilters.length == 1) {
            showNotification({
                message: "You do not have filtered search",
                type: "warning",
                autoClose: true,
                duration: 3
            });
            return;
        }
        var newDialog = new jDialog(ret, "", "", "300", "", function() {   
        });
        newDialog.themeDialog("modal2"); 
    },
    deleteFilter: function(id,obj) {
        // var conf = "Do you want to remove this permanently?";
        // jConfirm(conf, 'Confirmation Dialog','', '', '', function(r){
        //     if(r){
        var form_id = $(obj).attr("form_id");
        var wrapper = $("[form_id='" + form_id + "']");
        var action = "deleteFilter";
        $.post("/ajax/search",
                {
                    action: action,
                    id: id
                },
        function(data) {
            $("#row_" + id).fadeOut();
            wrapper.find(".loadRF").find("option[value='" + id + "']").remove();
        })
        //     }
        // })
    },
    showFilterConfirmation: function(obj) {
        $(obj).closest(dashboardItemContainer).find(".filterAction").fadeIn();
    },
    hideFilterConfirmation: function(obj) {
        $(obj).closest(dashboardItemContainer).find(".filterAction").fadeOut();
    },
    "setConfirmation": function(obj) {
        var ret = this.createModal(obj);
       var newDialog = new jDialog(ret, "", "", "200", "", function() {

        });
       newDialog.themeDialog("modal2");
    },
    createModal: function(obj) {
        var form_id = $(obj).closest(dashboardItemContainer).attr("form_id");

        var ret = '<h3 class="fl-margin-bottom"><i class="icon-print"></i> Filtered Request</h3>';
        ret += '<div class="hr"></div>';
        ret += '<div id="comment-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; overflow: hidden;" class="ps-container">'
        ret += '<div class="content-dialog fl-filter-title sub-container-comment requestComment" style="width: 100%;">';
        ret += '    <div class="pull-left" style="width: 100%">';
        ret += '        <div class="fields_below" style="margin-bottom: 10px;">';
        ret += '            <div class="label_below2">Filter Title: <font color="red">*</font></div>';
        ret += '        <div class="input_position_below" style="">';
        ret += '            <input type="text" name="" data-type="textbox" class="form-text filter_title"></div>';
        ret += '        </div>';
        ret += '    </div>';
        ret += '</div>';
        ret += '<div class="fields" style="">';
        ret += '<div class="label_basic"></div>';
        ret += '<div class="input_position" style="margin-top:5px;">';
        ret += ' <input type="button" class="btn-blueBtn fl-margin-right" id="saveRF" form_id="' + form_id + '" value="Save">';
        ret += ' <input type="button" class="btn-basicBtn" id="popup_cancel" value="Close">';
        ret += '</div>';
        ret += '</div>';
        return ret;
    },
    "saveRF": function(obj) {
        var search_value = jsonRequestData['search_value'];
        var search_field = jsonRequestData['field'];
        var multi_search = jsonRequestData['multi_search'];
        var title = $(".filter_title").val();
        var form_id = $(obj).attr("form_id");
        var date_field = jsonRequestData['date_field'];
        var date_from = jsonRequestData['date_from'];
        var date_to = jsonRequestData['date_to'];
        var wrapper = $("[form_id='" + form_id + "']");
        //save Request Filter
        if (title == "") {
            showNotification({
                message: "Please indicate your filter title.",
                type: "error",
                autoClose: true,
                duration: 3
            });
            return;
        }
        var err = 0;
        wrapper.find(".filterRequestsUser").find("option").each(function(){
            if(title==$(this).text()){
                err++;
                return true;
            }
            
        })
        if(err>0){
            showNotification({
                message: "Your title has already used.",
                type: "error",
                autoClose: true,
                duration: 3
            });
            return;
        }
        $.post("/ajax/search",
                {
                    action: "saveRequestFilter",
                    search_value: search_value,
                    search_field: search_field,
                    multi_search:  multi_search,
                    title: title,
                    form_id: form_id,
                    date_field: date_field,
                    date_from: date_from,
                    date_to: date_to
                }
        , function(data) {
            showNotification({
                message: "Filter has been saved",
                type: "success",
                autoClose: true,
                duration: 3
            });
            wrapper.find(".loadRF").append('<option value="' + data + '" '+ "multi_search='"+ multi_search +"'" +' search_value="' + search_value + '" search_field = "' + search_field + '" date_field = "' + date_field + '" date_from = "' + date_from + '" date_to = "' + date_to + '">' + title + '</option>');
            $("#popup_cancel").click();
            wrapper.find(".saveFC").slideUp();
            // $(".cancelLoadFRWrapper").slideUp();
            wrapper.find(".loadRF").val(0);
        })
    },
}

AdvanceFilter2 = {
    showDialog: function(obj) {
        var form_id = $(obj).closest(dashboardItemContainer).attr("form_id");
        var search_value = $(obj).closest(dashboardItemContainer).find(".searchRequestUsersValue").val();
        // var search_field = jsonRequestData['search_field'];
        var fields = $(obj).closest(dashboardItemContainer).find(".search-request-field").find("option");
        var fields_date = $(obj).closest(dashboardItemContainer).find(".search-request-field_date").find("option");
        var ret = '<h3 class="fl-margin-bottom"><i class="icon-cog"></i> Advance Filter</h3>';
        ret += '<div class="hr"></div>';
        ret += '<div id="advanceFilterContainer" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; overflow: hidden;" class="ps-container">'
        ret += '<div class="content-dialog">';
            ret += '<div class="" style="width:95%;margin-top: 15px;">';
                ret += '<h1 style="font-size:17px"><i class="icon-calendar"></i> Search Fields</h1>';
            ret += '</div>';
            ret += '<div class="searchFiltereWrapper" style="width:95%">';
                ret += ' <label><input type="checkbox" class="includeSearch"> Check if you do not want to include this.</label>';
                ret += ' <i class="deleteSearchFilter icon-minus-sign fa fa-minus cursor" style="float:right;display:none;margin-left: 5px;"></i>';

                ret += ' <i class="addSearchFilter icon-plus-sign fa fa-plus cursor" style="float:right"></i>';
                
                ret += '        <div class="" style="width:95%">';
                    ret += '        <div class="fields_below">';
                        ret += '        <div class="label_below2">Search Field: <font color="red">*</font></div>';
                        ret += '        <div class="input_position_below">';
                        ret += '            <select class="input-select search-request-field_filter" style="margin-top:0px;width: 100%;margin-right:0px;padding-top: 5px;">';
                                                for (var i in fields) {
                                                    if (fields[i]['value']) {
                                                        ret += '<option value="' + fields[i]['value'] + '">' + fields[i]['text'] + '</option>';
                                                    }
                                                }
                        ret += '            </select>';
                        ret += '        </div>';
                    ret += '        </div>';
                ret += '        </div>';
                ret += '        <div class="" style="width:95%">';
                    ret += '        <div class="fields_below" style="">';
                        ret += '        <div class="label_below2">Search Value: <font color="red">*</font></div>';
                        ret += '        <div class="input_position_below">';
                        ret += '                <select class="form-select search-request-operator">';
                        ret += '                    <option value="=">Equal (==)</option>';
                        ret += '                    <option value="<=">Less than equal (&lt;=)</option>';
                        ret += '                    <option value=">=">Greater than equal (&gt;=)</option>';
                        ret += '                    <option value=">">Greater than(&gt;)</option>';
                        ret += '                    <option value="<">Less than (&lt;)</option>';
                        ret += '                    <option value="!=">Not equal(!=)</option>';
                        ret += '                    <option value="%">Contains(%)</option>';
                        ret += '                </select>';
                        ret += '        </div>';
                    ret += '        </div>';
                ret += '        </div>';
                ret += '        <div class="" style="width:95%">';
                    ret += '        <div class="fields_below" style="">';
                        ret += '        <div class="label_below2">Search Value: <font color="red">*</font></div>';
                        ret += '        <div class="input_position_below">';
                        ret += '            <input type="text" name="" data-type="textbox" class="form-text search-request-value_filter" value="">';
                        ret += '        </div>';
                    ret += '        </div>';
                ret += '        </div>';
            ret += '        </div>';
            

        ret += '<div class="" style="width:95%;margin-top: 15px;">';
            ret += '<h1 style="font-size:17px"><i class="icon-calendar"></i> Date Range</h1>';
        ret += '</div>';
        ret += '<div class="dateRangeWrapper" style="width:95%">';
        ret += '        <div class="" style="width:95%">';
        ret += '        <div class="fields_below">';
        ret += '        <div class="label_below2">Search Field (Date): <font color="red">*</font></div>';
        ret += '        <div class="input_position_below">';
        ret += '            <select class="input-select search-request-field_filter_date" style="margin-top:0px;width: 100%;margin-right:0px;padding-top: 5px;">';
        ret += '<option value="0">-------Select-------</option>';
        for (var i in fields_date) {
            if (fields[i]['value']) {
                ret += '<option value="' + fields_date[i]['value'] + '">' + fields_date[i]['text'] + '</option>';
            }
        }
        ret += '            </select>';
        ret += '        </div>';
        ret += '        </div>';
        ret += '        </div>';
        ret += '        <div class="" style="border:1px solid transparent">';

        ret += '        </div>';
        ret += '        <div class="" style="width:95%">';
        ret += '        <div class="fields_below">';
        ret += '        <div class="input_position_below">';
        ret += '        <div class="label_below2">From: <font color="red">*</font></div>';
        ret += '            <input type="text" name="" data-type="textbox" class="form-text date_range search-request_date_from" value="">';
        ret += '        </div>';
        ret += '        </div>';
        ret += '        </div>';
        ret += '        <div class="" style="width:95%">';
        ret += '        <div class="fields_below" style="margin-top:-11px;">';
        ret += '        <div class="input_position_below" style="margin-top: 16px;">';
        ret += '        <div class="label_below2">To: <font color="red">*</font></div>';
        ret += '            <input type="text" name="" data-type="textbox" class="form-text date_range search-request_date_to" value="">';
        ret += '        </div>';
        ret += '        </div>';
        ret += '        </div>';
        ret += '</div>';
        ret += '<div class="fields">';
        ret += '<div class="label_basic"></div>';
        ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
        ret += ' <input type="button" class="btn-blueBtn fl-margin-right" id="advanceFilter" value="Filter" form_id="' + form_id + '">';
        ret += ' <input type="button" class="btn-basicBtn fl-margin-right" id="clearValue" value="Clear">';
        ret += ' <input type="button" class="btn-basicBtn" id="popup_cancel" value="Close">';
        ret += '</div>';
        ret += '</div>';
        ret += '</div>';
        
        var newDialog = new jDialog(ret, "", "600", "450", "", function() {   
        });
        newDialog.themeDialog("modal2"); 
        // $(".date_range").datetimepicker({
        //     dateFormat: 'yy-mm-dd'
        // });
        $(".search-request_date_from").datetimepicker({
            defaultDate: "+1w",
            changeMonth: true,
            dateFormat: 'yy-mm-dd',
            onClose: function(selectedDate) {
                $(".search-request_date_to").datetimepicker("option", "minDate", selectedDate);
            }
        });
        $(".search-request_date_to").datetimepicker({
            defaultDate: "+1w",
            changeMonth: true,
            dateFormat: 'yy-mm-dd',
            onClose: function(selectedDate) {
                $(".search-request_date_from").datetimepicker("option", "maxDate", selectedDate);
            }
        });
        if (search_value != "") {
            // $(".search-request-field_filter").val(search_field)
            // $(".search-request-value_filter").val(search_value);
        }

    },
    addFilter : function(){
        $("body").on("click",".addSearchFilter",function(){
            var html = "";
            html = $(this).closest(".searchFiltereWrapper").clone();
            html.find(".deleteSearchFilter").css("display","block");

            html.find(".includeSearch").prop("checked",false);
            html.find(".includeSearch").closest("label").css("display","none")
            html.find(".search-request-field_filter").val("TrackNo");
            html.find(".search-request-operator").val("=");
            html.find(".search-request-value_filter").val("");
            html.css("display","none");
            $(this).closest(".searchFiltereWrapper").after(html);
            html.fadeIn();
        })
    },
    deleteFilter : function(){
        $("body").on("click",".deleteSearchFilter",function(){
            $(this).closest(".searchFiltereWrapper").remove();
        })
    },
    filter: function(obj) {
        var form_id = $(obj).attr("form_id");
        // var search_value = $(".search-request-value_filter").val();
        // var search_field = $(".search-request-field_filter").val();
        var multi_search = [];

        var date_field = $(".search-request-field_filter_date").val();
        var date_from = $(".search-request_date_from").val();
        var date_to = $(".search-request_date_to").val();
        var wrapper = $("[form_id='" + form_id + "']");

        // jsonRequestData['search_value'] = search_value;
        // jsonRequestData['field'] = search_field;
        $(".searchFiltereWrapper").each(function(){
            if($(this).find(".includeSearch").prop("checked")==true){
                return true;
            }
            multi_search.push({
                "search_value":$(this).find(".search-request-value_filter").val(),
                "search_field":$(this).find(".search-request-field_filter").val(),
                "search_operator":$(this).find(".search-request-operator").val()
            })
        })
        console.log(multi_search);
        jsonRequestData['multi_search'] = JSON.stringify(multi_search);
        jsonRequestData['date_field'] = date_field;
        jsonRequestData['date_from'] = date_from;
        jsonRequestData['date_to'] = date_to;



        wrapper.find(".dataTable").dataTable().fnDestroy();
        GetRequestsDataTable.defaultData(jsonRequestData, wrapper.find(".dataTable"));
        RequestFilter2.showFilterConfirmation(wrapper.find(".dataTable"));
        $("#popup_cancel").click()
    },
    clearFilterFields: function() {
        $("#advanceFilterContainer").find("input[type='text'], select").each(function() {
            if ($(this).prop("tagName") == "INPUT") {
                $(this).val("")
            } else {
                $(this).val(0)
            }
        })
    }
}

GetOrgchartDataTable = {
    "defaultData" : function(){
        var oTable = $(".dataTable_orgchart").dataTable({
            "sDom": 'Rlfrtip',
            // "sScrollY": "400px",
            "oLanguage": {
                "sProcessing": '<div class="spinner load_m"> '+
                       '<div class="bar1"></div> '+
                       '<div class="bar2"></div> '+
                       '<div class="bar3"></div> '+
                       '<div class="bar4"></div> '+
                       '<div class="bar5"></div> '+
                       '<div class="bar6"></div> '+
                      '<div class="bar7"></div> '+
                      '<div class="bar8"></div> '+
                      '<div class="bar9"></div> '+
                      '<div class="bar10"></div> '+
                 '</div>'
            },
            "oColReorder" : false,
            "bLengthChange": false,
            "bFilter": false,
            "bProcessing": true,
            "bServerSide": true,
            "sPaginationType": "full_numbers",
            "bSort": false,
            "sAjaxSource": "/ajax/search",
            "fnServerData": function(sSource, aoData, fnCallback) {
                aoData.push({"name": "action", "value": "getOrgchartDataTable"});
                aoData.push({"name": "start", "value": "0"});
                aoData.push({"name": "search_value", "value": jsonOrgchartData['search_value']});
                aoData.push({"name": "column-sort", "value": jsonOrgchartData['column-sort']});
                aoData.push({"name": "column-sort-type", "value": jsonOrgchartData['column-sort-type']});
                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function(data) {
                        // console.log(data)
                        // return;
                        fnCallback(data);
                    }
                });
            },
            "fnInitComplete": function(oSettings, json) {
                
            }
        });
        return oTable;
    }
}
GetWorkflowDataTable = {
    "defaultData" : function(){
        var oTable = $(".dataTable_workflow").dataTable({
            "sDom": 'Rlfrtip',
            // "sScrollY": "400px",
            "oLanguage": {
                "sProcessing": '<div class="spinner load_m"> '+
                       '<div class="bar1"></div> '+
                       '<div class="bar2"></div> '+
                       '<div class="bar3"></div> '+
                       '<div class="bar4"></div> '+
                       '<div class="bar5"></div> '+
                       '<div class="bar6"></div> '+
                      '<div class="bar7"></div> '+
                      '<div class="bar8"></div> '+
                      '<div class="bar9"></div> '+
                      '<div class="bar10"></div> '+
                 '</div>'
            },
            "oColReorder" : false,
            "bLengthChange": false,
            "bFilter": false,
            "bProcessing": true,
            "bServerSide": true,
            "sPaginationType": "full_numbers",
            "bSort": false,
            "sAjaxSource": "/ajax/search",
            "fnServerData": function(sSource, aoData, fnCallback) {
                aoData.push({"name": "action", "value": "getWorkflowDataTable"});
                aoData.push({"name": "start", "value": "0"});
                aoData.push({"name": "search_value", "value": jsonWorkflowData['search_value']});
                aoData.push({"name": "column-sort", "value": jsonWorkflowData['column-sort']});
                aoData.push({"name": "column-sort-type", "value": jsonWorkflowData['column-sort-type']});
                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function(data) {
                        // console.log(data)
                        // return;
                        fnCallback(data);
                    }
                });
            },
            "fnInitComplete": function(oSettings, json) {
                
            }
        });
        return oTable;
    }
}
GetFormDataTable = {
    "defaultData" : function(){
        var oTable = $(".dataTable_form").dataTable({
            "sDom": 'Rlfrtip',
            // "sScrollY": "400px",
            "oLanguage": {
                "sProcessing": '<div class="spinner load_m"> '+
                       '<div class="bar1"></div> '+
                       '<div class="bar2"></div> '+
                       '<div class="bar3"></div> '+
                       '<div class="bar4"></div> '+
                       '<div class="bar5"></div> '+
                       '<div class="bar6"></div> '+
                      '<div class="bar7"></div> '+
                      '<div class="bar8"></div> '+
                      '<div class="bar9"></div> '+
                      '<div class="bar10"></div> '+
                 '</div>'
            },
            "oColReorder" : false,
            "bLengthChange": false,
            "bFilter": false,
            "bProcessing": true,
            "bServerSide": true,
            "sPaginationType": "full_numbers",
            "bSort": false,
            "sAjaxSource": "/ajax/search",
            "fnServerData": function(sSource, aoData, fnCallback) {
                aoData.push({"name": "action", "value": "getFormDataTable"});
                aoData.push({"name": "start", "value": "0"});
                aoData.push({"name": "search_value", "value": jsonFormData['search_value']});
                aoData.push({"name": "column-sort", "value": jsonFormData['column-sort']});
                aoData.push({"name": "column-sort-type", "value": jsonFormData['column-sort-type']});
                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function(data) {
                        // console.log(data)
                        // return;
                        fnCallback(data);
                    }
                });
            },
            "fnInitComplete": function(oSettings, json) {
                
            }
        });
        return oTable;
    }
}
GetReportDataTable = {
    "defaultData" : function(){
        var oTable = $(".dataTable_report").dataTable({
            "sDom": 'Rlfrtip',
            // "sScrollY": "400px",
            "oLanguage": {
                "sProcessing": '<div class="spinner load_m"> '+
                       '<div class="bar1"></div> '+
                       '<div class="bar2"></div> '+
                       '<div class="bar3"></div> '+
                       '<div class="bar4"></div> '+
                       '<div class="bar5"></div> '+
                       '<div class="bar6"></div> '+
                      '<div class="bar7"></div> '+
                      '<div class="bar8"></div> '+
                      '<div class="bar9"></div> '+
                      '<div class="bar10"></div> '+
                 '</div>'
            },
            "oColReorder" : false,
            "bLengthChange": false,
            "bFilter": false,
            "bProcessing": true,
            "bServerSide": true,
            "sPaginationType": "full_numbers",
            "bSort": false,
            "sAjaxSource": "/ajax/search",
            "fnServerData": function(sSource, aoData, fnCallback) {
                aoData.push({"name": "action", "value": "getReportsDataTable"});
                aoData.push({"name": "start", "value": "0"});
                aoData.push({"name": "search_value", "value": jsonReportData['search_value']});
                aoData.push({"name": "column-sort", "value": jsonReportData['column-sort']});
                aoData.push({"name": "column-sort-type", "value": jsonReportData['column-sort-type']});
                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function(data) {
                        // console.log(data)
                        // return;
                        fnCallback(data);
                    }
                });
            },
            "fnInitComplete": function(oSettings, json) {
                
            }
        });
        return oTable;
    }
}
GetCustomReportDataTable = {
    "defaultData" : function(){
        var oTable = $(".dataTable_custom_report").dataTable({
            "sDom": 'Rlfrtip',
            // "sScrollY": "400px",
            "oLanguage": {
                "sProcessing": '<div class="spinner load_m"> '+
                       '<div class="bar1"></div> '+
                       '<div class="bar2"></div> '+
                       '<div class="bar3"></div> '+
                       '<div class="bar4"></div> '+
                       '<div class="bar5"></div> '+
                       '<div class="bar6"></div> '+
                      '<div class="bar7"></div> '+
                      '<div class="bar8"></div> '+
                      '<div class="bar9"></div> '+
                      '<div class="bar10"></div> '+
                 '</div>'
            },
            "oColReorder" : false,
            "bLengthChange": false,
            "bFilter": false,
            "bProcessing": true,
            "bServerSide": true,
            "sPaginationType": "full_numbers",
            "bSort": false,
            "sAjaxSource": "/ajax/search",
            "fnServerData": function(sSource, aoData, fnCallback) {
                aoData.push({"name": "action", "value": "getCustomizeReportDataTable"});
                aoData.push({"name": "start", "value": "0"});
                aoData.push({"name": "search_value", "value": jsonCustomReportData['search_value']});
                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function(data) {
                        // console.log(data)
                        // return;
                        fnCallback(data);
                    }
                });
            },
            "fnInitComplete": function(oSettings, json) {
                
            }
        });
        return oTable;
    }
}